﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.FrameEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using Tools;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SysFramework;
using Microsoft.VisualBasic;
using log4net;
using static System.Net.Mime.MediaTypeNames;
using System.Diagnostics;
using System.Collections;

namespace BLL
{
    public class U8Order : PubMethod
    {
        HttpAgreement http;
        Commands cmd;
        ReturnResult rsl;
        ILog log ;
        List<InOutResult> resultList;
        OutBaseHelper outBase;

        public U8Order()
        {
            http = new HttpAgreement();
            cmd = new Commands();
            log = LogManager.GetLogger(this.GetType().Name);
            resultList = new List<InOutResult>();
            outBase=new OutBaseHelper();
        }
        /// <summary>
        /// u8接口登录信息参数构建
        /// </summary>
        /// <param name="uTable"></param>
        /// <returns></returns>
        public Dictionary<string, object> createUserPar(string userCode, string baseCode, ref string errMsg)
        {
            StringBuilder sb = new StringBuilder();
            //var sAccID = Tools.ConfigReader.Reader["sAccID"];//账套号
            var sAccID = baseCode;
            var sys = new Dictionary<string, object>();
            sys["sAccID"] = sAccID;
            sys["sYear"] = DateTime.Now.Year;
            sys["sDate"] = getNowDate();
            sys["sServer"] = AppSettingHelper.ReadAppSettings("BaseServerIP"); 
            if (userCode == "admin")
            {
                if (baseCode == "002")
                {
                    sys["sUserID"] = "demo";
                    sys["sUserName"] = "demo";
                }
                else
                {
                    sys["sUserID"] = "001";
                    sys["sUserName"] = "孔维先";

                }

                sys["sPassword"] = "";

            }
            else
            {
                sb.Append("select * from sys_users_info where userCode='" + userCode + "'");
                sb.Append(" and isSync='Y' and isDel='0' and status='Y' ");
                sb.Append(" and baseCode='" + sAccID + "'");
                var uTable = cmd.GetDataTable(sb.ToString());
                if (uTable.Rows.Count < 1)
                {
                    errMsg = "该账号无权限提交数据";
                    return null;
                }
                sys["sUserID"] = uTable.Rows[0]["userCode"].ToString();
                sys["sUserName"] = uTable.Rows[0]["userName"].ToString();
                if (string.IsNullOrWhiteSpace(uTable.Rows[0]["openPwd"].ToString()))
                {
                    errMsg = "系统密码与U8密码不匹配请先修改密码";
                    return null;
                }
                sys["sPassword"] = uTable.Rows[0]["openPwd"].ToString();
            }

            return sys;
        }


        /// <summary>
        /// 其他入库   （废料入库）
        /// </summary>
        /// <param name="usCode">提交人员信息</param>
        /// <returns></returns>
        public ReturnResult FlOtherIn(DataTable datas,string usCode,string baseCode,string wareHouse, string dept,string rdcode,string isBlue="1")
        {
            rsl = new ReturnResult();
            try
            {
                if (datas.Rows.Count<0)
                {
                    rsl.Result = false;
                    rsl.Message = "传入的数据为空";
                    return rsl;
                }
                var pars = new Dictionary<string, object>();

                string msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                #region 构建参数
                pars["System"] = sysPar;
                #region 表头参数
                var head = new Dictionary<string, object>();
                head["ccode"] = DateTime.Now.ToString("yyyyMMddHHmmss");//单据号
                head["cwhcode"] = wareHouse;//发生仓库
                head["ddate"] = getNow(); //日期
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人
                head["crdcode"] = rdcode;//发生类型
                head["cdepcode"] = dept;//发生部门
                pars["Head"] = head;
                #endregion

                #region 表体数据
                var cList = new List<Dictionary<string, object>>();
                for (int i = 0; i < datas.Rows.Count; i++)
                {
                    var ldic = new Dictionary<string, object>();
                    ldic["cinvcode"] = datas.Rows[i]["proCode"]; //存货编码，string类型
                    ldic["cinvname"] = datas.Rows[i]["proName"]; //存货名称，string类型

                    var bBatch = false;
                    var result = checkInv(datas.Rows[i]["proCode"].ToString(), baseCode);
                    if (result == "True")
                    {
                        bBatch = true;
                    }
                    else if (result == "False")
                    {
                        bBatch = false;
                    }

                    if(!string.IsNullOrWhiteSpace(datas.Rows[i]["cu_batch"].ToString()) && bBatch)
                    {
                        ldic["cbatch"] = datas.Rows[i]["cu_batch"]; //批次，string类型
                    }
                    
                    ldic["iquantity"] = datas.Rows[i]["number"]; //数量（平米数/重量），double类型
                    cList.Add(ldic);
                }
                pars["List"] = cList;
                #endregion
                pars["isBlue"] = isBlue;//红蓝单
                #endregion

                var postData = JsonConvert.SerializeObject(pars);
                var url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), "OtherIn");
                var info = http.PostJson(url, postData);
                log.Info(string.Format("其他入库单,参数：{0},结果：{1}", postData, info));

                if (!string.IsNullOrWhiteSpace(info))
                {
                    return JsonConvert.DeserializeObject<ReturnResult>(info);
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        } 
        
        /// <summary>
        /// 材料出库  
        /// </summary>
        /// <param name="usCode">提交人员信息</param>
        /// <returns></returns>
        public ReturnResult MaterialOut(List<DbTempScanData> datas, string baseCode, string usCode)
        {
            rsl = new ReturnResult();
            InOutResult or = new InOutResult();
            try
            {
                if (string.IsNullOrWhiteSpace(datas[0].tempCode))
                {
                    rsl.Result = false;
                    rsl.Message = "传入的临时码为空";
                    return rsl;
                }

                List<string> tempCodes = new List<string>();
                var pars = new Dictionary<string, object>();
                string msg = "";

                var type = datas[0].inOutType;
                if (!string.IsNullOrEmpty(datas[0].operateCode) && (datas[0].operateCode == "pibg" || datas[0].operateCode == "pobg"))
                {
                    type = datas[0].operateCode;//版辊
                }
                var paraData = this.MaterialOutData(datas[0].tempCode, type, baseCode, ref msg);
                var data = (List<Dictionary<string, string>>)paraData["dataList"];

                //获取调用接口的条码
                var bars = new List<string>();
                foreach (var s in datas)
                {
                    bars.Add(s.barCode);
                }

                //版辊出库时，data.Count <=0 即全都出过库，此处不生成材料出库单，只改版辊状态，和记录计划用料、出入库记录
                //版辊出库时，出库类别只有不是“生产使用”，不生成材料出库单，只改版辊状态，和记录计划用料、出入库记录
                if (data.Count <= 0 || (datas[0].operateCode == "pobg" && datas[0].inOutType != "scsy"))
                //if (data.Count <= 0 || (datas[0].inOutType=="pobg" && datas[0].operateCode != "scsy"))
                {
                    or.SuccOrderCode = "000";
                    or.SuccBarCodes = bars;
                    rsl.Result = true;
                    resultList.Add(or);
                    rsl.Data = resultList;
                    return rsl;
                }


                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg; //获取出库数据出错
                    return rsl;
                }
                if (bars == null || bars.Count <= 0)
                {
                    rsl.Result = false;
                    rsl.Message = "没有获取调用接口的数据条码";
                    return rsl;
                }
                msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                #region 构建参数
                pars["System"] = sysPar;
                #region 表头参数
                var head = new Dictionary<string, object>();
                head["ccode"] = DateTime.Now.ToString("yyyyMMddHHmmss");//单据号
                head["cwhcode"] = datas[0].wareHouse;//发生仓库
                head["ddate"] = datas[0].happenDate; //日期
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人
                head["crdcode"] = datas[0].typeCode;//发生类型
                head["cdepcode"] = datas[0].operateDept;//发生部门

                head["cdefine1"] = datas[0].outOrderCode;//关联计划

                pars["Head"] = head;
                #endregion

                #region 表体数据
                var cList = new List<Dictionary<string, object>>();
                for (int i = 0; i < data.Count; i++)
                {
                    var ldic = new Dictionary<string, object>();
                    //ldic["irowno"] = data[i]["irow"].ToString();//行号
                    ldic["cinvcode"] = data[i]["proCode"]; //存货编码，string类型
                    ldic["cinvname"] = data[i]["proName"]; //存货名称，string类型
                    ldic["iquantity"] = data[i]["quantity"]; //数量（平米数/重量），double类型
                    ldic["cbatch"] = data[i]["batch"];//批号
                    ldic["iunitcost"] = data[i]["iunitcost"];//单价
                    ldic["iprice"] = data[i]["iprice"];//金额
                    if (data[i].ContainsKey("byCode") &&!string.IsNullOrWhiteSpace(data[i]["byCode"].ToString()))
                        ldic["cfree1"] = data[i]["byCode"];//版号
                    //ldic["cposition"] = data[i]["goodsPosition"];//货位
                    cList.Add(ldic);
                }
                pars["List"] = cList;
                #endregion
                pars["isBlue"] = datas[0].isBlue;//红蓝单
                #endregion

                var postData = JsonConvert.SerializeObject(pars);

                log.Info(string.Format("材料出库单,参数：{0}", postData));

                string url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), "MaterialOut");
                msg = http.PostJson(url, postData);
                log.Info(string.Format("材料出库单,参数：{0},结果：{1}", postData, msg));

                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl = JsonConvert.DeserializeObject<ReturnResult>(msg);
                    //InOutResult or = new InOutResult();
                    if (rsl.Result)
                    {
                        or.SuccOrderCode = rsl.Data.ToString();
                        or.SuccBarCodes = bars;
                        rsl.Result = true;
                    }
                    else
                    {
                        ErrorResult er = new ErrorResult();
                        er.ErrorMsg = rsl.Message;
                        er.BarCodes = bars;
                        or.ErrorInfo = er;
                    }

                    resultList.Add(or);
                    rsl.Data = resultList;
                    return rsl;
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 材料出库数据
        /// </summary>
        /// <param name="tempCode"></param>
        /// <returns></returns>
        private Dictionary<string, object> MaterialOutData(string tempCode,string inOutType, string baseCode, ref string errMsg)
        {
            Dictionary<string, object> returnDic = new Dictionary<string, object>();
            List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>();

            StringBuilder sb = new StringBuilder();
            if(inOutType=="pobg" || inOutType == "pibg")
            {
                //版辊信息
                sb.Append("select b.erpProCode proCode,b.byCode ,i.proName,isBlue,'1' barNumber,b.batch,PPlan,b.money ");
                sb.Append("from bar_TempScanData_info t  ");
                sb.Append("inner join fun_BanYang_list b on t.barCode= b.byBarCode ");
                sb.Append("inner join fun_Inventory_Info i on i.proCode= b.erpProCode ");
                sb.Append("where tempCode='" + tempCode + "' and (PPlan is Null or PPlan='') ");
                sb.Append("group by b.erpProCode,b.byCode,i.proName,isBlue,b.batch,PPlan,b.money ");
            }
            else
            {
                string type = getCPProType();  // //获取成品大类

                //条码信息  按存货批次汇总
                sb.Append("select b.proCode,'' byCode,proName,");
                sb.Append("case when b.typeCode like '"+ type + "%' then '' else cu_batch end batch,");  // cu_batch batch,
                sb.Append("isBlue,sum(convert(decimal(18,2),b.number)) barNumber ");
                sb.Append("from bar_TempScanData_info t  ");
                sb.Append("inner join V_BarCode_Info b on t.barCode= b.barCode ");
                sb.Append("where tempCode='" + tempCode + "' ");
                sb.Append("group by b.proCode,b.typeCode,proName,cu_batch ,isBlue");
            }
            
            var table = cmd.GetDataTable(sb.ToString());   

            Dictionary<string, string> dic;
            var irow = 0;

            PlanBLL plan = new PlanBLL();
            foreach (DataRow r in table.Rows)
            {
                var quantity = "0";//主计量(数量)
              
                if (r["isBlue"].ToString().Equals("1"))
                {
                    quantity = r["barNumber"].ToString();
                }
                else
                {
                    quantity = "-" + r["barNumber"].ToString();
                }

                irow++;
                dic = new Dictionary<string, string>();
                dic["irow"] = irow.ToString();
                dic["proCode"] = r["proCode"].ToString();
                dic["proName"] = r["proName"].ToString();
                dic["quantity"] = quantity;
                dic["batch"] = r["batch"].ToString();//批号

                var price = "0";//单价
                if (inOutType == "pobg" || inOutType == "pibg")
                {
                    price = r["money"].ToString();
                    dic["byCode"] = r["byCode"].ToString();//版号
                }
                else
                    price = plan.getProUprice(r["proCode"].ToString(), r["batch"].ToString());     //获取存货某个批次最新单价  采购的

                var money = (decimal.Parse(quantity) * decimal.Parse(price)).ToString();

                dic["iunitcost"] = price;//单价
                dic["iprice"] = money;//金额
                dic["batchMemo"] = "";//批次备注
                dataList.Add(dic);
            }
            returnDic.Add("dataList", dataList);
            return returnDic;
        }

        /// <summary>
        /// 产成品入库  
        /// </summary>
        /// <param name="usCode">提交人员信息</param>
        /// <returns></returns>
        public ReturnResult productIn(List<DbTempScanData> tempDatas, string baseCode, string usCode)
        {
            rsl = new ReturnResult();
            List<InOutResult> resultList = new List<InOutResult>();
            List<string> bars = new List<string>();
            try
            {
                var pars = new Dictionary<string, object>();
                string msg = "";
                var datas = this.InData(tempDatas[0].tempCode, ref msg, ref bars);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                if (bars == null || bars.Count <= 0)
                {
                    rsl.Result = false;
                    rsl.Message = "没有获取调用接口的数据条码";
                    return rsl;
                }

                msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                pars["System"] = sysPar;

                #region 表头参数
                var head = new Dictionary<string, object>();
                head["ccode"] = DateTime.Now.ToString("yyyyMMddHHmmss");//单据号
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人
                head["ddate"] = tempDatas[0].happenDate; //发生日期
                head["cwhcode"] = tempDatas[0].wareHouse; //仓库
                head["crdcode"] = tempDatas[0].typeCode; //业务类型
                head["cdepcode"] = tempDatas[0].operateDept;//发生部门
                pars["Head"] = head;
                #endregion

                #region 表体数据
                pars["List"] = datas;
                #endregion
                pars["isBlue"] = tempDatas[0].isBlue;

                string url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), "ProductIn");
                var postData = JsonConvert.SerializeObject(pars);

                msg = http.PostJson(url, postData);
                log.Info(string.Format("产成品入库,参数：{0},结果：{1}", postData, msg));

                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var apiResult = JsonConvert.DeserializeObject<ReturnResult>(msg);
                    InOutResult or = new InOutResult();
                    if (apiResult.Result)
                    {
                        or.SuccOrderCode = apiResult.Data.ToString();
                        or.SuccBarCodes = bars;
                    }
                    else
                    {
                        ErrorResult er = new ErrorResult();
                        er.ErrorMsg = apiResult.Message;
                        er.BarCodes = bars;
                        or.ErrorInfo = er;
                    }
                    resultList.Add(or);
                    rsl.Result = true;
                    rsl.Data = resultList;
                    return rsl;
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        //获取成品大类
        private string getCPProType()
        {
            string type = "05";
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("seleCt parValue from sys_parameters_info where parCode = 'cpProType' ");
                var table = cmd.GetDataTable(sb.ToString());
                if(table.Rows.Count > 0 )
                {
                    type = table.Rows[0][0].ToString();
                }
            }
            catch (Exception rx)
            {

            }

            return type;
        }
        

        /// <summary>
        /// 入库数据
        /// </summary>
        /// <param name="tempCode">临时码</param>
        /// <param name="msg">错误消息</param>
        /// <param name="barList">关联条码</param>
        /// <param name="needPC">是否传批次（产成品入库不传）</param>
        /// <returns></returns>
        private List<Dictionary<string, string>> InData(string tempCode, ref string msg, ref List<string> barList)
        {
            List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>();

            string type = getCPProType();  //获取成品大类

            StringBuilder sb = new StringBuilder();
            sb.Append("select case when typeCode like '"+ type + "%' then '' else cu_batch end cu_batch,");
            sb.Append("b.* from V_BarCode_Info b ");
            sb.Append("where b.barCode in(select barCode from bar_TempScanData_info ");
            sb.Append("where tempCode='" + tempCode + "')");
            var table = cmd.GetDataTable(sb.ToString());
            List<string> reList = new List<string>();

            Dictionary<string, string> dic;
            int rowCount = 0;
            foreach (DataRow r in table.Rows)
            {
                barList.Add(r["barCode"].ToString());
                dic = new Dictionary<string, string>();
                string proCode = r["proCode"].ToString();//存货编码

                if (!reList.Contains(proCode))
                {
                    rowCount++;
                    dic["cinvcode"] = proCode;
                    dic["cinvname"] = r["proName"].ToString();
                    dic["iquantity"] = r["number"].ToString();
                    if (!string.IsNullOrEmpty(r["cu_batch"].ToString())) 
                    {
                        dic["cbatch"] = r["cu_batch"].ToString();
                    }
                    dataList.Add(dic);

                    reList.Add(r["proCode"].ToString());
                }
                else
                {
                    for (int i = 0; i < dataList.Count; i++)
                    {
                        if (dataList[i]["cinvcode"] == r["proCode"].ToString())
                        {
                            dataList[i]["iquantity"] = Convert.ToString(double.Parse(dataList[i]["iquantity"]) + double.Parse(r["number"].ToString()));
                            break;
                        }
                    }
                }
            }

            return dataList;
        }

        /// <summary>
        /// 检查存货自由项属性（批次）
        /// </summary>
        public string checkInv(string proCode,string baseCode)
        {
            string rsl = "";
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.Append("select bInvBatch from inventory where cinvcode='" + proCode + "'");
                var dt = outBase.getData(sb.ToString(), baseCode);
                if (dt.Rows.Count > 0)
                {
                    rsl = dt.Rows[0][0].ToString();
                }
            }
            catch (Exception ex)
            {
                rsl = ex.Message;
            }

            return rsl;
        }

        /// <summary>
        /// 出入库通用方法【产成品入库、材料出库】  直接传条码信息，不通过临时码
        /// </summary>
        /// <param name="usCode">提交人员信息</param>
        /// <returns></returns>
        public ReturnResult tyInOut(List<Dictionary<string, string>> datas,List<string> bars,string wareHouse,string crdcode,string dept, string baseCode, string usCode,string typeCode,string isBlue="1")
        {
            rsl = new ReturnResult();
            List<InOutResult> resultList = new List<InOutResult>();
            try
            {
                var pars = new Dictionary<string, object>();
                string msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                pars["System"] = sysPar;

                #region 表头参数
                var head = new Dictionary<string, object>();
                head["ccode"] = DateTime.Now.ToString("yyyyMMddHHmmss");//单据号
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人
                head["ddate"] = getNowDate(); //发生日期
                head["cwhcode"] = wareHouse; //仓库
                head["crdcode"] = crdcode; //业务类型
                head["cdepcode"] = dept;//发生部门
                if (datas[0].ContainsKey("plCode") && !string.IsNullOrEmpty(datas[0]["plCode"].ToString()))
                    head["cdefine1"] = datas[0]["plCode"].ToString();//材料出库关联计划号
                pars["Head"] = head;
                #endregion

                #region 表体数据
                List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>();
                Dictionary<string, string> dic;
                List<string> reList = new List<string>();

                var bBatch = false;

                foreach (var r in datas)
                {
                    dic = new Dictionary<string, string>();
                    string proCode = r["proCode"].ToString();//存货编码

                    if (!reList.Contains(proCode))
                    {
                        dic["cinvcode"] = proCode;
                        dic["cinvname"] = r["proName"].ToString();
                        dic["iquantity"] = r["number"].ToString();

                        bBatch = false;
                        var result = checkInv(proCode, baseCode);
                        if(result == "True")
                        {
                            bBatch = true;
                        }
                        else if (result == "False")
                        {
                            bBatch = false;
                        }
                        
                        if (!string.IsNullOrEmpty(r["cu_batch"].ToString()) && bBatch)
                        {
                            dic["cbatch"] = r["cu_batch"].ToString();
                        }
                        if (r.ContainsKey("iunitcost") && !string.IsNullOrEmpty(r["iunitcost"].ToString()))
                        {
                            dic["iunitcost"] = r["iunitcost"].ToString();
                            dic["iprice"] = r["iprice"].ToString();
                        }
                        dataList.Add(dic);

                        reList.Add(r["proCode"].ToString());
                    }
                    else
                    {
                        for (int i = 0; i < dataList.Count; i++)
                        {
                            if (dataList[i]["cinvcode"] == r["proCode"].ToString())
                            {
                                dataList[i]["iquantity"] = Convert.ToString(double.Parse(dataList[i]["iquantity"]) + double.Parse(r["number"].ToString()));
                                break;
                            }
                        }
                    }
                }
                pars["List"] = dataList;
                #endregion
                pars["isBlue"] = isBlue;

                string url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), typeCode);
                var postData = JsonConvert.SerializeObject(pars);

                msg = http.PostJson(url, postData);
                //log.Info(string.Format("产成品入库,参数：{0},结果：{1}", postData, msg));
                log.Info(string.Format("出入库通用方法"+ typeCode + ",参数：{0},结果：{1}", postData, msg));

                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var apiResult = JsonConvert.DeserializeObject<ReturnResult>(msg);
                    InOutResult or = new InOutResult();
                    if (apiResult.Result)
                    {
                        or.SuccOrderCode = apiResult.Data.ToString();
                        or.SuccBarCodes = bars;
                    }
                    else
                    {
                        ErrorResult er = new ErrorResult();
                        er.ErrorMsg = apiResult.Message;
                        er.BarCodes = bars;
                        or.ErrorInfo = er;
                    }
                    resultList.Add(or);
                    rsl.Result = true;
                    rsl.Data = resultList;
                    return rsl;
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 销售出库
        /// </summary>
        /// <param name="tempDatas"></param>
        /// <param name="usCode"></param>
        /// <returns></returns>
        public ReturnResult SaleOut(List<DbTempScanData> tempDatas, string baseCode, string usCode)
        {
            rsl = new ReturnResult();
            resultList = new List<InOutResult>();
            try
            {
                if (string.IsNullOrWhiteSpace(tempDatas[0].tempCode))
                {
                    rsl.Result = false;
                    rsl.Message = "传入的临时码为空";
                    return rsl;
                }
                log.Info("销售出库单开始执行");
                List<string> tempCodes = new List<string>();
                var pars = new Dictionary<string, object>();
                string msg = "";
                var paraData = this.wareOutData(tempDatas[0].tempCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    log.Info("销售出库错误【wareOutData】：" + msg);
                    return rsl;
                }
                var data = (List<Dictionary<string, string>>)paraData["dataList"];
                var bars = (List<string>)paraData["barList"];
                if (bars == null || bars.Count <= 0)
                {
                    rsl.Result = false;
                    rsl.Message = "没有获取调用接口的数据条码";
                    return rsl;
                }
                msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    log.Info("销售出库错误【createUserPar】：" + msg);
                    return rsl;
                }
                #region 构建参数
                pars["System"] = sysPar;
                #region 表头参数
                var dlid = "";   //发货退货单主表标识 
                var head = new Dictionary<string, object>();
                head["ccode"] = DateTime.Now.ToString("yyyyMMddHHmmss");//单据号
                head["cwhcode"] = tempDatas[0].wareHouse;//发生仓库
                head["ddate"] = tempDatas[0].happenDate; //日期
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人
                head["ccuscode"] = tempDatas[0].customCode;//客户编码
                head["crdcode"] = tempDatas[0].typeCode;//发生类型
                head["cdepcode"] = tempDatas[0].operateDept;//发生部门
                head["cbuscode"] = tempDatas[0].outOrderCode;//发货单号


                var listDic = getDisPatchList(tempDatas[0].outOrderCode, baseCode, ref dlid);
                if (listDic == null || listDic.Count < 1)
                {
                    rsl.Message = "未获取发货单信息";
                    return rsl;
                }

                head["cdlcode"] = dlid;//发货单主表id
                head["cstcode"] = listDic[0]["cSTCode"];  //销售类型编码 
                pars["Head"] = head;
                #endregion

                #region 表体数据
                var cList = new List<Dictionary<string, object>>();

                for (int i = 0; i < data.Count; i++)
                {
                    var ldic = new Dictionary<string, object>();
                    ldic["cinvcode"] = data[i]["proCode"]; //存货编码，string类型
                    ldic["iquantity"] = data[i]["quantity"]; //数量
                    ldic["isodid"] = data[i]["isodid"];   //销售订单子表ID 
                    ldic["iorderdid"] = data[i]["iorderdid"]; //订单子表id 
                    ldic["idlsid"] = data[i]["idlsid"]; //发货退货单子表标识 
                    if (data[i].ContainsKey("batch") && !string.IsNullOrEmpty(data[i]["batch"].ToString()))
                    {
                        ldic["cbatch"] = data[i]["batch"].ToString();
                    }
                    cList.Add(ldic);
                }
                pars["List"] = cList;
                #endregion

                pars["isBlue"] = tempDatas[0].isBlue;//红蓝单
                #endregion

                var postData = JsonConvert.SerializeObject(pars);
                string url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), "SaleOut");
                log.Info("传入接口的数据" + url + "\n" + postData);
                msg = http.PostJson(url, postData);
                log.Info(string.Format("销售出库单,参数：{0},结果：{1}", postData, msg));
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl = JsonConvert.DeserializeObject<ReturnResult>(msg);
                    InOutResult or = new InOutResult();
                    if (rsl.Result)
                    {
                        or.SuccOrderCode = rsl.Data.ToString();
                        or.SuccBarCodes = bars;
                    }
                    else
                    {
                        ErrorResult er = new ErrorResult();
                        er.ErrorMsg = rsl.Message;
                        er.BarCodes = bars;
                        or.ErrorInfo = er;
                    }
                    resultList.Add(or);
                    rsl.Result = true;
                    rsl.Data = resultList;
                    return rsl;
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
                log.Info("销售出库异常：" + ex.Message);
            }
            return rsl;
        }

        /// <summary>
        /// 出库数据
        /// </summary>
        /// <param name="tempCode"></param>
        /// <returns></returns>
        private Dictionary<string, object> wareOutData(string tempCode, string baseCode, ref string errMsg)
        {
            Dictionary<string, object> returnDic = new Dictionary<string, object>();
            List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>();
            StringBuilder sb = new StringBuilder();
            errMsg = "";
            try
            {
                string type = getCPProType();  //获取成品大类

                sb.Append("select b.barCode,b.proCode,proName,");
                sb.Append("case when b.typeCode like '"+ type + "%' then '' else cu_batch end  batch ,"); //   cu_batch batch
                sb.Append("isBlue,b.number barNumber ,");
                sb.Append("b.cu_iUnitCost price, CONVERT(decimal(18, 2), isnull(b.number, 0)) * CONVERT(decimal(18, 2), isnull(b.cu_iUnitCost, 0)) total ");
                sb.Append(",t.inOutType,t.outOrderCode ");
                sb.Append("from bar_TempScanData_info t  ");
                //sb.Append("inner join bar_ProductBarCode_info b on t.barCode= b.barCode ");
                sb.Append("inner join V_BarCode_Info b on t.barCode= b.barCode ");
                sb.Append("where tempCode='" + tempCode + "' ");

                var table = cmd.GetDataTable(sb.ToString());

                List<string> reList = new List<string>();
                List<string> barList = new List<string>();
                Dictionary<string, string> dic;
                var irow = 0;

                foreach (DataRow r in table.Rows)
                {
                    //获取调用接口的条码
                    if (!barList.Contains(r["barCode"].ToString()))
                    {
                        barList.Add(r["barCode"].ToString());
                    }
                    double quantity = 0;//主计量(数量)

                    if (r["isBlue"].ToString().Equals("1"))
                    {
                        quantity +=double.Parse( r["barNumber"].ToString());
                    }
                    else
                    {
                        quantity -= double.Parse(r["barNumber"].ToString());
                    }
                    if (quantity== 0)
                    {
                        errMsg = "条码数量错误，主计量数量不能为0";
                        return returnDic;
                    }
                    var s = r["proCode"].ToString();
                    if (!string.IsNullOrEmpty(r["batch"].ToString()))
                    {
                        s += "-" + r["batch"].ToString();
                    }

                    if (!reList.Contains(s))
                    {
                        #region 根据存货、批次号构建数据(不存在进行添加)
                        irow++;
                        dic = new Dictionary<string, string>();
                        dic["irow"] = irow + "";//行号
                        dic["proCode"] = r["proCode"].ToString();
                        dic["proName"] = r["proName"].ToString();
                        dic["quantity"] = quantity.ToString();

                        if (!string.IsNullOrEmpty(r["batch"].ToString()))
                        {
                            dic["batch"] = r["batch"].ToString();
                        }

                        dic["price"] = r["price"].ToString();
                        dic["total"] = r["total"].ToString();

                        var dlid = "";
                        if (r["inOutType"].ToString().Equals("pos"))
                        {
                            #region 销售出库 查找关联发货单
                            this.getDisPatchList(r["outOrderCode"].ToString(), baseCode, ref dlid);
                            var para = new Dictionary<string, object>();
                            para["proCode"] = r["proCode"].ToString();

                            var dispatchList = this.getDisPatchsList(dlid, baseCode, para);
                            if (dispatchList == null || dispatchList.Count < 1)
                            {
                                errMsg = "未找到发货单数据";
                                log.Info("未找到发货单数据:" + r["outOrderCode"].ToString() + JsonConvert.SerializeObject(para));
                                return null;
                            }
                            dic["isodid"] = dispatchList[0]["iSOsID"];
                            dic["iorderdid"] = dispatchList[0]["iSOsID"];
                            dic["idlsid"] = dispatchList[0]["iDLsID"];
                            #endregion
                        }

                        //dic["batchMemo"] = "";//批次备注
                        dataList.Add(dic);
                        reList.Add(s);
                        #endregion
                    }
                    else
                    {
                        #region 货号、批次存在进行数据累加
                        for (int i = 0; i < dataList.Count; i++)
                        {
                            if (dataList[i]["proCode"] == r["proCode"].ToString() && 
                                (dataList[i].ContainsKey("batch") && dataList[i]["batch"] == r["batch"].ToString() || !dataList[i].ContainsKey("batch")) 
                                )
                            {
                                dataList[i]["quantity"] = (double.Parse(dataList[i]["quantity"]) + quantity).ToString();
                                dataList[i]["total"] = (double.Parse(dataList[i]["total"]) + double.Parse(r["total"].ToString())).ToString();
                                break;
                            }
                        }
                        #endregion
                    }
                }
                returnDic.Add("barList", barList);
                returnDic.Add("dataList", dataList);
                return returnDic;
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
                log.Info("wareOutData异常："+ ex.Message);
                return returnDic;
            }
        }
        /// <summary>
        /// 根据关联单号查找发货退货单主表标识
        /// </summary>
        /// <param name="cCode"></param>
        /// <param name="baseCode"></param>
        /// <param name="DLID"></param>
        /// <returns></returns>
        private List<Dictionary<string, string>> getDisPatchList(string cCode, string baseCode, ref string DLID)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("select * from DispatchList");
            sb.Append(" where 1=1 and cDLCode='" + cCode + "'");
            var dispatchList = outBase.getData(sb.ToString(), baseCode);
            if (dispatchList.Rows.Count > 0)
            {
                DLID = dispatchList.Rows[0]["DLID"].ToString();
            }
            return cmd.TableToDictionary(dispatchList);
        }
        /// <summary>
        /// 根据发货退货单主表标识 查找子表关联存货数据
        /// </summary>
        /// <param name="dlid"></param>
        /// <param name="baseCode"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        private List<Dictionary<string, string>> getDisPatchsList(string dlid, string baseCode, Dictionary<string, object> dic)
        {
            var proCode = dic["proCode"].ToString();
            StringBuilder sb = new StringBuilder();
            sb.Append("select iSOsID,iDLsID from DispatchLists");
            sb.Append(" where 1=1 and dlid='" + dlid + "' and cInvCode='" + proCode + "' ");

            var dispatchList = outBase.getData(sb.ToString(), baseCode);
            return cmd.TableToDictionary(dispatchList);
        }

        /// <summary>
        /// 其他入库
        /// </summary>
        /// <param name="tempDatas">扫描数据</param>
        /// <param name="usCode">提交人员信息</param>
        /// <returns></returns>
        public ReturnResult OtherIn(List<DbTempScanData> tempDatas, string baseCode, string usCode)
        {
            rsl = new ReturnResult();
            List<InOutResult> resultList = new List<InOutResult>();
            List<string> bars = new List<string>();
            try
            {
                var pars = new Dictionary<string, object>();
                string msg = "";
                var datas = this.InData(tempDatas[0].tempCode, ref msg, ref bars);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                pars["System"] = sysPar;

                #region 表头参数
                var head = new Dictionary<string, object>();
                head["ccode"] = DateTime.Now.ToString("yyyyMMddHHmmss");//单据号
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人
                head["ddate"] = tempDatas[0].happenDate; //发生日期
                head["cwhcode"] = tempDatas[0].wareHouse; //仓库
                head["crdcode"] = tempDatas[0].typeCode; //业务类型
                head["cdepcode"] = tempDatas[0].operateDept;//发生部门
                pars["Head"] = head;
                #endregion

                #region 表体数据
                pars["List"] = datas;
                #endregion
                pars["isBlue"] = tempDatas[0].isBlue; 

                string url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), "OtherIn");
                var postData = JsonConvert.SerializeObject(pars);

                msg = http.PostJson(url, postData);
                log.Info(string.Format("其他入库,参数：{0},结果：{1}", postData, msg));

                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var apiResult = JsonConvert.DeserializeObject<ReturnResult>(msg);
                    InOutResult or = new InOutResult();
                    if (apiResult.Result)
                    {
                        or.SuccOrderCode = apiResult.Data.ToString();
                        or.SuccBarCodes = bars;
                    }
                    else
                    {
                        ErrorResult er = new ErrorResult();
                        er.ErrorMsg = apiResult.Message;
                        er.BarCodes = bars;
                        or.ErrorInfo = er;
                    }
                    resultList.Add(or);
                    rsl.Result = true;
                    rsl.Data = resultList;
                    return rsl;
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 其他出库
        /// </summary>
        /// <param name="tempDatas"></param>
        /// <param name="usCode"></param>
        /// <returns></returns>
        public ReturnResult OtherOut(List<DbTempScanData> tempDatas, string baseCode, string usCode)
        {
            rsl = new ReturnResult();
            List<InOutResult> resultList = new List<InOutResult>();
            try
            {
                List<string> tempCodes = new List<string>();
                var pars = new Dictionary<string, object>();
                string msg = "";
                var paraData = this.wareOutData(tempDatas[0].tempCode, baseCode, ref msg);
                var data = (List<Dictionary<string, string>>)paraData["dataList"];
                var bars = (List<string>)paraData["barList"];
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                if (bars == null || bars.Count <= 0)
                {
                    rsl.Result = false;
                    rsl.Message = "没有获取调用接口的数据条码";
                    return rsl;
                }
                msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }

                #region 构建参数
                pars["System"] = sysPar;

                #region 表头参数
                var head = new Dictionary<string, object>();
                head["ccode"] = DateTime.Now.ToString("yyyyMMddHHmmss");//单据号
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人
                head["ddate"] = tempDatas[0].happenDate; //发生日期
                head["cwhcode"] = tempDatas[0].wareHouse; //仓库
                head["crdcode"] = tempDatas[0].typeCode; //业务类型
                head["cdepcode"] = tempDatas[0].operateDept;//发生部门
                pars["Head"] = head;
                #endregion

                #region 表体数据
                var cList = new List<Dictionary<string, object>>();

                for (int i = 0; i < data.Count; i++)
                {
                    var ldic = new Dictionary<string, object>();
                    ldic["cinvcode"] = data[i]["proCode"]; //存货编码，string类型
                    ldic["iquantity"] = data[i]["quantity"]; //数量，double类型
                    if (data[i].ContainsKey("batch") && !string.IsNullOrEmpty(data[i]["batch"].ToString()))
                    {
                        ldic["cbatch"] = data[i]["batch"].ToString();
                    }
                    cList.Add(ldic);
                }
                pars["List"] = cList;
                #endregion
                pars["isBlue"] = tempDatas[0].isBlue;

                #endregion

                string url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), "OtherOut");
                var postData = JsonConvert.SerializeObject(pars);

                msg = http.PostJson(url, postData);
                log.Info(string.Format("其他出库,参数：{0},结果：{1}", postData, msg));

                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var apiResult = JsonConvert.DeserializeObject<ReturnResult>(msg);
                    InOutResult or = new InOutResult();
                    if (apiResult.Result)
                    {
                        or.SuccOrderCode = apiResult.Data.ToString();
                        or.SuccBarCodes = bars;
                    }
                    else
                    {
                        ErrorResult er = new ErrorResult();
                        er.ErrorMsg = apiResult.Message;
                        er.BarCodes = bars;
                        or.ErrorInfo = er;
                    }
                    resultList.Add(or);
                    rsl.Result = true;
                    rsl.Data = resultList;
                    return rsl;
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 调拨单
        /// </summary>
        /// <param name="tempDatas"></param>
        /// <param name="usCode"></param>
        /// <returns></returns>
        public ReturnResult WareHouseChanage(List<DbTempScanData> tempDatas, string baseCode, string usCode,string spCode=null)
        {
            rsl = new ReturnResult();
            try
            {
                var pars = new Dictionary<string, object>();
                string msg = "";
                var paraData = new Dictionary<string, object>();
                paraData = this.wareOutData(tempDatas[0].tempCode, baseCode, ref msg);

                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }

                var data = (List<Dictionary<string, string>>)paraData["dataList"];
                var bars = (List<string>)paraData["barList"];
                
                if (bars == null || bars.Count <= 0)
                {
                    rsl.Result = false;
                    rsl.Message = "没有获取调用接口的数据条码";
                    return rsl;
                }
                msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                pars["System"] = sysPar;
                #region 调拨单表头参数
                var head = new Dictionary<string, object>();
                head["ctvcode"] = DateTime.Now.ToString("yyyyMMddHHmmss");//单据号
                head["dtvdate"] = tempDatas[0].happenDate; //日期
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人

                //从材料出库界面做的调拨
                if (!string.IsNullOrWhiteSpace(spCode))
                {
                    #region 获取参数
                    var sql = "select parValue,parCode from sys_parameters_info where parCode in ('spPOMType','work_warehouse_code','paw_Rd_Style') and isDel=0 and enable='open'";
                    var t= cmd.GetDataTable(sql);//获取参数

                    var wh = "8";
                    var itype = "14";  //旭日 14   本地 62
                    var otype = "24";  //旭日 24   本地 73

                    var rows= t.Select("parCode='work_warehouse_code'");
                    if(rows.Length > 0)
                    {
                        var wStr = rows[0]["parValue"].ToString();
                        wh = wStr.Split(',')[0].ToString();//Ning   获取第一个
                    }
                    rows = t.Select("parCode='paw_Rd_Style'");
                    if (rows.Length > 0)
                    {
                        var types = JsonConvert.DeserializeObject<JObject>(rows[0]["parValue"].ToString());
                        otype = types["happen"].ToString();
                        itype = types["target"].ToString();
                    }

                    #endregion

                    head["ciwhcode"] = wh; //转入仓库   车间库
                    head["cowhcode"] = tempDatas[0].wareHouse;//转出仓库
                    head["cordcode"] = otype;//发生/出库类型
                    head["cirdcode"] = itype;//目标/入库类型
                }
                else
                {
                    head["ciwhcode"] = tempDatas[0].targetWareHouse; //转入仓库
                    head["cowhcode"] = tempDatas[0].wareHouse;//转出仓库
                    head["cordcode"] = tempDatas[0].typeCode;//发生/出库类型
                    head["cirdcode"] = tempDatas[0].targetTypeCode;//目标/入库类型
                }

                //head["cverifyperson"] = sysPar["sUserName"].ToString();
                //head["dverifydate"] = tempDatas[0].happenDate;
                //head["cpersoncode"] = tempDatas[0].cPersonCode;
                head["cpersoncode"] = usCode;
                pars["Head"] = head;
                #endregion

                #region 表体数据
                var cList = new List<Dictionary<string, object>>();

                for (int i = 0; i < data.Count; i++)
                {
                    var ldic = new Dictionary<string, object>();
                    ldic["cinvcode"] = data[i]["proCode"]; //存货编码
                    ldic["itvquantity"] = data[i]["quantity"].ToString(); //数量
                    if (data[i].ContainsKey("batch") && !string.IsNullOrEmpty(data[i]["batch"].ToString()))
                    {
                        ldic["ctvbatch"] = data[i]["batch"].ToString();
                    }
                    ldic["itvacost"] = data[i]["price"].ToString();   //单价
                    ldic["itvaprice"] = data[i]["total"].ToString();  //金额
                    //ldic["cinposcode"] = data[i]["targetGoodsPosition"];//调入货位
                    //ldic["coutposcode"] = data[i]["goodsPosition"];//调出货位

                    cList.Add(ldic);
                }
                pars["List"] = cList;
                #endregion
                pars["isBlue"] = tempDatas[0].isBlue;

                string url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), "TransVouch");
                var postData = JsonConvert.SerializeObject(pars);
                msg = http.PostJson(url, postData);
                log.Info(string.Format("调拨出入参数,参数：{0},结果：{1}", postData, msg));
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl = JsonConvert.DeserializeObject<ReturnResult>(msg);
                    InOutResult or = new InOutResult();
                    if (rsl.Result)
                    {
                        or.SuccOrderCode = rsl.Data.ToString();
                        or.SuccBarCodes = bars;
                        rsl.Result = true;
                    }
                    else
                    {
                        ErrorResult er = new ErrorResult();
                        er.ErrorMsg = rsl.Message;
                        er.BarCodes = bars;
                        or.ErrorInfo = er;
                    }
                    resultList.Add(or);
                    rsl.Data = resultList;
                    return rsl;
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 请购单
        /// </summary>
        /// <returns></returns>
        public ReturnResult PurchaseRequisition(JObject table,List<JObject> datas, string usCode, string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                #region 非空验证
                if (datas.Count < 0)
                {
                    rsl.Result = false;
                    rsl.Message = "传入的数据为空";
                    return rsl;
                }
                if (table.Count < 0)
                {
                    rsl.Result = false;
                    rsl.Message = "未获取到计划存货信息";
                    return rsl;
                }
                #endregion
                var pars = new Dictionary<string, object>();

                string msg = "";
                var sysPar = this.createUserPar(usCode, baseCode, ref msg);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    rsl.Message = msg;
                    return rsl;
                }
                #region 构建参数
                pars["System"] = sysPar;
                var proArr=table["plProName"].ToString().Split('/');

                string memo = "生产计划:"+table["plCode"].ToString()+",客户:"+ table["cuName"].ToString() + " ,需要生产存货:" + proArr[0].Trim() +" ( "+ proArr[1].Trim() + " ) ，计划生产:"+ proArr[2].Trim() + " ";//请购原因
                #region 表体数据
                var cList = new List<Dictionary<string, object>>();
                for (int i = 0; i < datas.Count; i++)
                {
                    //memo += "子件"+ datas[i]["proName"] + ",需要"+ datas[i]["bzValue"]+",现存量"+ datas[i]["number"]+",可用数量"+ datas[i]["kyNum"]+",采购数量"+ datas[i]["memo"]+"。";
                    var ldic = new Dictionary<string, object>();
                    ldic["cinvcode"] = datas[i]["proCode"]; //存货编码，string类型
                    //ldic["cinvname"] = datas[i]["proName"]; //存货名称，string类型
                    ldic["drequirdate"] = getNowDate(); //需求日期，string类型
                    if( decimal.Parse(datas[i]["memo"].ToString())==0)
                    {
                        ldic["fquantity"] = "0.01"; //请购数量（平米数/重量），double类型
                        ldic["cdefine25"] = decimal.Parse(datas[i]["memo"].ToString()).ToString("0.00"); //请购数量（平米数/重量），double类型
                    }
                    else
                    {
                        ldic["fquantity"] = datas[i]["memo"]; //请购数量（平米数/重量），double类型
                        ldic["cdefine25"] = decimal.Parse(datas[i]["memo"].ToString()).ToString("0.00"); //请购数量（平米数/重量），double类型
                    }
                    //ldic["fquantity"] = datas[i]["memo"]; //请购数量（平米数/重量），double类型

                    ldic["cdefine22"] = decimal.Parse(datas[i]["number"].ToString()).ToString("0.00"); //现存数量（平米数/重量），double类型
                    ldic["cdefine23"] = decimal.Parse(datas[i]["bzValue"].ToString()).ToString("0.00"); //需求数量（平米数/重量），double类型
                    ldic["cdefine24"] = decimal.Parse(datas[i]["kyNum"].ToString()).ToString("0.00"); //可用数量（平米数/重量），double类型

                    ldic["cdefine26"] = datas[i]["meter"].ToString(); //米数，double类型

                    cList.Add(ldic);
                }
                pars["List"] = cList;
                #endregion

                #region 表头参数
                var head = new Dictionary<string, object>();
                head["ddate"] = getNowDate(); //日期
                head["cmaker"] = sysPar["sUserName"].ToString();//制单人 
                head["cpersoncode"] = sysPar["sUserID"].ToString();//请购人（业务员）  旭日业务员编码和登录人编码是一样的
                head["cmemo"] = memo;//备注，此处存请购原因
                pars["Head"] = head;
                #endregion

                #endregion

                var postData = JsonConvert.SerializeObject(pars);
                var url = string.Format("{0}{1}", AppSettingHelper.ReadAppSettings("APIUrl"), "PurchaseRequisition");
                var info = http.PostJson(url, postData);
                log.Info(string.Format("请购单,参数：{0},结果：{1}", postData, info));

                if (!string.IsNullOrWhiteSpace(info))
                {
                    return JsonConvert.DeserializeObject<ReturnResult>(info);
                }
                else
                {
                    rsl.Message = "接口结果返回为空";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


    }

}
